package mks.webshop.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mks.webshop.Workspace;
import mks.webshop.common.AC;
import mks.webshop.entity.BasePanel;
import mks.webshop.entity.Category;
import mks.webshop.entity.Counter;
import mks.webshop.entity.Logo;
import mks.webshop.entity.Notice;
import mks.webshop.entity.Order;
import mks.webshop.entity.OrderDetail;
import mks.webshop.entity.PanelType;
import mks.webshop.entity.Product;
import mks.webshop.entity.User;
import mks.webshop.entity.Food;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.UserServiceFactory;

@Controller
@SessionAttributes
public class WebshopController {
    static final Logger LOG = Logger.getLogger("WebshopController");
    
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    
    /** Default workspace with Vietnamese language. . */
    Workspace ws = new Workspace(AC.VN);

    /**
     * Xử lý khi gọi trang home
     * Lấy nội dung của right, header, footer panel truyền vào session tương ứng,
     * Lấy danh sách Category ở level 1 lưu vào session catListMain
     * Kiểm tra danh sách Category ở level 1: nếu rỗng thì chèn 1 category giả (nonecat); nếu có category thì lấy danh sách category ra
     * @param session
     * @return
     */
    @RequestMapping("/home")
    public ModelAndView showHome(HttpSession session) {
        ModelAndView mav;
        Workspace ws = new Workspace(AC.VN); 

        BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
        
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
        
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);

        session.setAttribute("address", "home");
        List<Product> modList = ws.getAllProductList();
        List<Notice> allNoticeList = ws.getAllNoticeList();
        List<Food> allFoodList = ws.getAllFoodList();
        
        if (allNoticeList != null){
        	List<Notice> modNoticeList = ws.getNoticeWithQuantity(allNoticeList, 4);
        	List<Notice> noticeList = ws.inverseNoticeList(modNoticeList);
            session.setAttribute("noticeList", noticeList);
        }
        
        if(allFoodList != null){
        	List<Food> modFoodList = ws.getFoodWithQuantity(allFoodList, 4);
        	List<Food> noticeList = ws.inverseFoodList(modFoodList);
        	session.setAttribute("allFoodList", noticeList);
        }
        if (session.getAttribute("proList") == null){
        	if (modList != null){
            	List<Product> proList = ws.getProductWithQuantity(modList, 18);
                session.setAttribute("proList", proList);
            }
        }
        
        int increament = 0;
        Boolean isNewSession = (Boolean)session.getAttribute("newSession"); 
        if(isNewSession == null){
        	session.setAttribute("newSession", true);
        	increament = 1;
        }
        
        long sequence;
        Counter counter = new Counter();
        ws.saveCounter(counter, increament);
        Counter count  = ws.getCounter();
        if(count == null){
        	sequence = 0;
        }else{
        	sequence = count.getCount();
        }
        
       
        session.setAttribute("newSession", false);
        session.setAttribute("error", 0);
        session.setAttribute("counter", sequence);
        mav = new ModelAndView("home");
        return mav;
    }
    
    @RequestMapping("/contact")
    public ModelAndView showContact(HttpSession session){
    	ModelAndView mav;
        Workspace ws = new Workspace(AC.VN);
      //Get content of introduction panel
        BasePanel contactPanel = ws.getPanel(PanelType.CONTACT);
        session.setAttribute("address", "contact");
        session.setAttribute("contactPanel", contactPanel);
        session.setAttribute("error", 0);
        mav = new ModelAndView("contact");
        return mav;
    }
    @RequestMapping("/listproduct")
   public ModelAndView listsubcategory(@RequestParam("id") String catid,  HttpSession session) {
        ModelAndView mav = null;
        Workspace ws = new Workspace(AC.VN);
        String nameCat = new String("");
        String subNameCat = new String("");
        
        if (catid.equals("saleoff")){
        	nameCat = "Sản phẩm khuyến mãi";
        }else if (catid.equals("vegetable1")){
        	subNameCat = "Rau, củ, quả";
        	nameCat ="Rau ăn lá";
        }else if (catid.equals("vegetable2")){
        	subNameCat = "Rau, củ, quả";
        	nameCat ="Củ, quả";
        }else if (catid.equals("vegetable3")){
        	subNameCat = "Rau, củ, quả";
        	nameCat ="Rau gia vị";
        }else if (catid.equals("fruit")){
        	nameCat = "Trái cây";
        }else if (catid.equals("fish")){
        	nameCat = "Cá";
        	subNameCat = "Hải sản";
        }else if (catid.equals("seafood1")){
        	nameCat = "Hải sản";
        	subNameCat = "Hải sản";
        }else if (catid.equals("meat")){
        	nameCat = "Thịt";
        }else if (catid.equals("water")){
        	nameCat = "Nước uống";
        }else if (catid.equals("driedfood")){
        	nameCat = "Hàng khô";
        }else if (catid.equals("good")){
        	nameCat = "Hàng tiêu dùng";
        }else if (catid.equals("canned")){
        	nameCat = "Đồ hộp";
        }else if (catid.equals("frozen")){
        	nameCat = "Đồ đông lạnh";
        }else if (catid.equals("rice")){
        	nameCat = "Gạo, nếp, tấm";
        }else if (catid.equals("milk")){
        	nameCat = "Sữa";
        }else if (catid.equals("flower")){
        	nameCat = "Hoa tươi";
        }else if (catid.equals("giavi")){
        	nameCat = "Gia vị";
        }

//        LOG.finest("Cat Id: " + catid);
//        LOG.finest("Name Cat:" + nameCat);
//        List<Product> modList = ws.getSubProductList(catid);
//        if (modList != null){
//        	List<Product> proList = ws.inverseList(modList);
//            session.setAttribute("productlist", proList);
//        }else{
//        	session.setAttribute("productlist", modList);
//        }

        	List<Product> modList = ws.getSubProductListSortingName(catid);
            if (modList != null){
            	List<Product> proList = ws.inverseList(modList);
                session.setAttribute("productlist", proList);
            }else{
            	session.setAttribute("productlist", modList);
            }

        
        session.setAttribute("catid", catid);
        session.setAttribute("nameCat", nameCat);
        session.setAttribute("subNamecat", subNameCat);
        session.setAttribute("address", "listproduct");
        session.setAttribute("error", 0);
        mav = new ModelAndView("listproduct");
        return mav;
    }
    
    @RequestMapping("/listsaleoff")
    public ModelAndView listsaleoff(HttpSession session) {
         ModelAndView mav = null;
         Workspace ws = new Workspace(AC.VN);
         List<Product> proList = ws.getAllSaleOffProductList();
//         for (Product pro:proList){
//     		System.out.print(pro.getName());
//         }
         if(session.getAttribute("listsaleoff") == null){
        	 session.setAttribute("listsaleoff", proList);
         }        
         session.setAttribute("address", "listsaleoff");
         session.setAttribute("error", 0);
         mav = new ModelAndView("listsaleoff");
         return mav;
     }
    /*
    @RequestMapping("/listproduct")
    public ModelAndView listproduct() {
        return new ModelAndView("listproduct"); 
    }

    @RequestMapping("/subcategory")
    public ModelAndView showSubCateogry() {
        return new ModelAndView("subcategory"); 
    }
    */
//    @RequestMapping("/allcategory")
//    public void all(){
//    	Workspace ws = new Workspace(AC.VN);
//    	String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
//    	List<Category> catListFull = ws.getAllCategoryList();
//    	for (Category cat:catListFull){
//    		System.out.println(cat.getName());
//    		System.out.println(cat.getId());
//    	}
//    	
//    }
    
    @RequestMapping("/detailproduct")
    public ModelAndView detailProduct(@RequestParam("id") String proid,  HttpSession session){
    ModelAndView mav = null;	
   	Workspace ws = new Workspace(AC.VN);
   	Product pro = ws.getProductById(proid);
   	String catid = pro.getCatId();
   	String nameCat = new String ();
   	String subNameCat = new String("");
   	if (catid.equals("saleoff")){
    	nameCat = "Sản phẩm khuyến mãi";
    }else if (catid.equals("vegetable1")){
    	subNameCat = "Rau, củ, quả";
    	nameCat ="Rau ăn lá";
    }else if (catid.equals("vegetable2")){
    	subNameCat = "Rau, củ, quả";
    	nameCat ="Củ, quả";
    }else if (catid.equals("vegetable3")){
    	subNameCat = "Rau, củ, quả";
    	nameCat ="Rau gia vị";
    }else if (catid.equals("fruit")){
    	nameCat = "Trái cây";
    }else if (catid.equals("fish")){
    	nameCat = "Cá";
    	subNameCat = "Hải sản";
    }else if (catid.equals("seafood1")){
    	nameCat = "Hải sản";
    	subNameCat = "Hải sản";
    }else if (catid.equals("meat")){
    	nameCat = "Thịt";
    }else if (catid.equals("water")){
    	nameCat = "Nước uống";
    }else if (catid.equals("driedfood")){
    	nameCat = "Hàng khô";
    }else if (catid.equals("good")){
    	nameCat = "Hàng tiêu dùng";
    }else if (catid.equals("canned")){
    	nameCat = "Đồ hộp";
    }else if (catid.equals("frozen")){
    	nameCat = "Đồ đông lạnh";
    }else if (catid.equals("rice")){
    	nameCat = "Gạo, nếp, tấm";
    }else if (catid.equals("milk")){
    	nameCat = "Sữa";
    }else if (catid.equals("flower")){
    	nameCat = "Hoa tươi";
    }else if (catid.equals("giavi")){
    	nameCat = "Gia vị";
    }
   	
   	session.setAttribute("catid", catid);
   	session.setAttribute("product", pro);
   	session.setAttribute("nameCat", nameCat);
   	session.setAttribute("subNamecat", subNameCat);
    session.setAttribute("address", "detailproduct");
    session.setAttribute("error", 0);
   	mav = new ModelAndView("detailproduct");
   	
   	
   	return mav;
    }

    @RequestMapping("/introduction")
    public ModelAndView showIntroduction(HttpSession session) {
    	ModelAndView mav;
        Workspace ws = new Workspace(AC.VN); 
//        String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
        List<Category> catListMain = ws.getCategoryList();
        if (catListMain.isEmpty()) {
            Category noneCat = new Category();
            noneCat.setId("0");
            noneCat.setName("Empty Category");
            noneCat.setLevel(1);
            catListMain = new ArrayList<Category>();
            catListMain.add(noneCat);
        }
        List<Category> catListFull = ws.getAllCategoryList();
        session.setAttribute("fullcategorylist", catListFull);
        session.setAttribute("maincategorylist", catListMain);
        // Get content of right panel
        BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
        
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
        
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);
        
        //Get content of introduction panel
        BasePanel introductionPanel = ws.getPanel(PanelType.INTRODUCTION);
        session.setAttribute("introductionPanel", introductionPanel);
        session.setAttribute("address", "introduction");
        session.setAttribute("error", 0);
        mav = new ModelAndView("introduction");

        return mav; 
    }
    @RequestMapping("/help")
    public ModelAndView showHelp(HttpSession session) {
    	ModelAndView mav;
        Workspace ws = new Workspace(AC.VN);
//        String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
//        List<Category> catListMain = ws.getCategoryList();
//        if (catListMain.isEmpty()) {
//            Category noneCat = new Category();
//            noneCat.setId("0");
//            noneCat.setName("Empty Category");
//            noneCat.setLevel(1);
//            catListMain = new ArrayList<Category>();
//            catListMain.add(noneCat);
//        }
//        List<Category> catListFull = ws.getAllCategoryList();
//        session.setAttribute("fullcategorylist", catListFull);
//        session.setAttribute("maincategorylist", catListMain);
        // Get content of right panel
        BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
        
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
        
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);
        
        //Get content of help panel
        BasePanel helpPanel = ws.getPanel(PanelType.HELP);
        session.setAttribute("helpPanel", helpPanel);
        session.setAttribute("address", "help");
        session.setAttribute("error", 0);
        mav = new ModelAndView("help");

        return mav;  
    }
    
    @RequestMapping("/subcategory_raucuqua")
    public ModelAndView showSubcategory_raucuqua(HttpSession session){
    	ModelAndView mav;
    	Workspace ws = new Workspace(AC.VN);
    	mav = new ModelAndView("subcategory_raucuqua");
    	return mav;
    }
    
    @RequestMapping("/policy")
    public ModelAndView showPolicy(HttpSession session) {
    	ModelAndView mav;
        Workspace ws = new Workspace(AC.VN); 
//        String lang = (String) session.getAttribute(AC.LANG);
//        Workspace ws = new Workspace(lang);
//        List<Category> catListMain = ws.getCategoryList();
//        if (catListMain.isEmpty()) {
//            Category noneCat = new Category();
//            noneCat.setId("0");
//            noneCat.setName("Empty Category");
//            noneCat.setLevel(1);
//            catListMain = new ArrayList<Category>();
//            catListMain.add(noneCat);
//        }
//        List<Category> catListFull = ws.getAllCategoryList();
//        session.setAttribute("fullcategorylist", catListFull);
//        session.setAttribute("maincategorylist", catListMain);
        // Get content of right panel
        BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
        session.setAttribute("rightPanel", rightPanel);
        
        // Get content of header panel
        BasePanel headerPanel = ws.getPanel(PanelType.HEADER);
        session.setAttribute("headerPanel", headerPanel);
        
        // Get content of footer panel
        BasePanel footerPanel = ws.getPanel(PanelType.FOOTER);
        session.setAttribute("footerPanel", footerPanel);
        
        //Get content of policy panel
        BasePanel policyPanel = ws.getPanel(PanelType.POLICY);
        session.setAttribute("policyPanel", policyPanel);
        session.setAttribute("address", "policy");
        session.setAttribute("error", 0);
        mav = new ModelAndView("policy");

        return mav; 
    }
    
 
    
	@RequestMapping("/display.html")
    public void displayImage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BlobKey blobKey = new BlobKey(req.getParameter("imageKey"));
        blobstoreService.serve(blobKey, resp);
    }
    
  
    @RequestMapping("/admin_tab")
    public ModelAndView magTab() {
        return new ModelAndView("admin_tab"); 
    }
    
    @RequestMapping(value = "/logout.do", method= RequestMethod.GET)
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();

        String logoutUrl = UserServiceFactory.getUserService().createLogoutURL("/home.html");

        response.sendRedirect(logoutUrl);
    }
    
    @RequestMapping("/listnotice")
    public ModelAndView showListNoticePage(HttpSession session) {
         ModelAndView mav = null;
         Workspace ws = new Workspace(AC.VN);
         List<Notice> allNoticeList = ws.getAllNoticeList();
         
         session.setAttribute("allNoticeList", allNoticeList);
         if (allNoticeList != null){
         	List<Notice> modNoticeList = ws.getNoticeWithQuantity(allNoticeList, 4);
         	List<Notice> noticeList = ws.inverseNoticeList(modNoticeList);
             session.setAttribute("noticeList", noticeList);
         }
         BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
         session.setAttribute("rightPanel", rightPanel);
         session.setAttribute("address", "listnotice");
         session.setAttribute("error", 0);
         mav = new ModelAndView("listnotice");
         return mav;
     }
    
    @RequestMapping("/detailnotice")
    public ModelAndView detailNotice(@RequestParam("id") String id,  HttpSession session){
    ModelAndView mav = null;	
   	Workspace ws = new Workspace(AC.VN);
   	Notice note = ws.getNoticeById(id);
   	session.setAttribute("notice", note);
    session.setAttribute("address", "detailnotice");
    session.setAttribute("error", 0);
   	mav = new ModelAndView("detailnotice");
   	return mav;
    }
    
    @RequestMapping("/userregister.html")
    public ModelAndView showRegisterPage(HttpSession session){
    	ModelAndView mav = null;
    	User user = new User();
    	mav = new ModelAndView("userregister");
    	mav.addObject(user);
    	return mav;
    }
    
    @RequestMapping(value = "/processregister.di")
    public String processRegister(HttpSession session, HttpServletRequest req) throws IOException{
    	Workspace ws = new Workspace(AC.VN);
    	String name = req.getParameter("name");
    	String password1 = req.getParameter("password1");
    	String password2 = req.getParameter("password2");
    	String email1 = req.getParameter("email1");
    	String email2 = req.getParameter("email2");
    	String id = req.getParameter("id");
    	User temUser = ws.getUserById(id);
    	String phonenumber = req.getParameter("phonenumber");
    	if ((name == "") || (password1 == "") || (email1 == "") || (id == "") || (phonenumber == "")){
    		session.setAttribute("error", 9);
    		return "redirect:userregister.html";
    	}
    	else if (temUser != null){
    		session.setAttribute("error", 8);
    		return "redirect:userregister.html";
    	}
    	else if (!password1.equals(password2)){
    		session.setAttribute("error", 5);
    		return "redirect:userregister.html";
    	}else if (!email1.equals(email2)){
    		session.setAttribute("error", 6);
    		return "redirect:userregister.html";
    	}else {
    		User user = new User();
    		user.setId(id);
    		user.setPassword(password1);
    		user.setEmail(email1);
    		user.setName(name);
    		user.setPhonenumber(phonenumber);
    		user.setOldpassword("");
    		user.setDeliveryNo("");
    		user.setDeliveryStreet("");
    		user.setDeliveryWard("");
    		user.setDeliveryDistrict("");
    		ws.save(user);
    		session.setAttribute("error", 7);
    		return "redirect:userregister.html";
    	}
    }
	
	///Controller show Food
    @RequestMapping("/listfood")
    public ModelAndView showListFoodPage(HttpSession session) {
         ModelAndView mav = null;
         Workspace ws = new Workspace(AC.VN);
         List<Food> list = ws.getAllFoodList();
         session.setAttribute("allFoodList", list);
         if (list != null){
          	List<Food> modFoodList = ws.getFoodWithQuantity(list, 4);
          	List<Food> foodList = ws.inverseFoodList(modFoodList);
              session.setAttribute("allFoodList", foodList);
          }
         
         BasePanel rightPanel = ws.getPanel(PanelType.RIGHT);
         session.setAttribute("rightPanel", rightPanel);
         session.setAttribute("address", "listfood");
         mav = new ModelAndView("listfood");
         return mav;
     }
    
    @RequestMapping("/detailfood")
    public ModelAndView detailFood(@RequestParam("id") String code,  HttpSession session){
	    ModelAndView mav = null;	
	   	Workspace ws = new Workspace(AC.VN);
	   	Food food = ws.getFoodByCode(code);
	   	session.setAttribute("food", food);
	    session.setAttribute("address", "detailfood");
	   	mav = new ModelAndView("detailfood");	
	   	return mav;
    }
    
    @RequestMapping("/search.di")
    public ModelAndView listSearchProduct(@RequestParam("name") String name, HttpSession session){
    	ModelAndView mav = null;	
	   	Workspace ws = new Workspace(AC.VN);
	   	List<Product> productlist = ws.getListProductByName(name);
	   	session.setAttribute("productlist", productlist);
	   	session.setAttribute("address", "listsearchedproduct");
	   	mav = new ModelAndView("listsearchedproduct");

	   	return mav;
    }
    
    @RequestMapping("/detailuser")
    public ModelAndView showDetailUserPage(@RequestParam("id") String id){
    	ModelAndView mav = null;
    	Workspace ws = new Workspace(AC.VN);
    	User modUser = ws.getUserById(id);
    	mav = new ModelAndView("detailuser");
    	mav.addObject("user", modUser);
    	return mav;
    }
    
    @RequestMapping("/listuser")
    public ModelAndView showListUserPage(HttpSession session){
    	ModelAndView mav = null;
    	Workspace ws = new Workspace(AC.VN);
    	List<User> listUser = ws.getAllUser();
    	session.setAttribute("listuser", listUser);
    	mav = new ModelAndView("listuser");
    	return mav;
    }
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/saveorder.html")
    public String saveOrder(HttpServletRequest request,  HttpSession session){
		
		String deliveryPhone = request.getParameter("deliveryPhone");
		String deliveryNo = request.getParameter("deliveryNo");
		String deliveryStreet = request.getParameter("deliveryStreet");
		String deliveryWard = request.getParameter("deliveryWard");
		String deliveryDistrict = request.getParameter("deliveryDistrict");
		String deliveryTime = request.getParameter("deliveryTime");
		String deliveryNote = request.getParameter("deliveryNote");
		String recieverName = request.getParameter("recieverName");
	   	Workspace ws = new Workspace(AC.VN);
	   	Order order = (Order)session.getAttribute("order");
	   	List<OrderDetail> list = (List<OrderDetail>)session.getAttribute("booking");
	   	
	   	String username = (String)session.getAttribute("username");
	   	User user = ws.getUserById(username);
	   
	   	
	   	if("".equals(user.getDeliveryNo()) && "".equals(user.getDeliveryStreet()) && "".equals(user.getDeliveryWard()) && "".equals(user.getDeliveryDistrict())){
	   		user.setDeliveryNo(deliveryNo);
	   		user.setDeliveryStreet(deliveryStreet);
	   		user.setDeliveryWard(deliveryWard);
	   		user.setDeliveryDistrict(deliveryDistrict);
	   		ws.save(user);
	   	}
	   	
	   	order.setCustomerName(recieverName);
	   	order.setCustomerPhone(deliveryPhone);
	   	order.setCustomerEmail(user.getEmail());
	   	order.setDeliveryNo(deliveryNo);
	   	order.setDeliveryStreet(deliveryStreet);
	   	order.setDeliveryWard(deliveryWard);
	   	order.setDeliveryDistrict(deliveryDistrict);
	   	order.setDeliveryTime(deliveryTime);
	   	order.setDeleveryNote(deliveryNote);
	   	order.setShipping(10000);
	   	order.setIsDone(false);
	   	ws.saveOrder(order);
	   	
	   	for (OrderDetail orderDetail : list) {
	   		ws.saveOrderDetail(orderDetail);
		}
	   	
	   	order.setCode(null);
	   	order.setBasePrice(0);
	   	order.setTotalPrice(0);
	   	
	   	list.clear();
	 
	   	return "shoppingdone"; 
    }
    
    @RequestMapping("/loginuser.html")
    public String login(HttpServletRequest request,  HttpSession session){
   	 	
    	String username = request.getParameter("username");
    	String password = request.getParameter("password");

    	if (!"".equals(username) && !"".equals(password)){
    		
    		Workspace ws = new Workspace(AC.VN);
    		boolean check = ws.checkLogin(username, password);
    
    		if(check){
    			Order order = new Order();
    			List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
    			session.setAttribute("username", username);
    			session.setAttribute("order", order);
    			session.setAttribute("booking", orderDetails);
    			return "loginsuccess";
    		}	
    	}
    	return "fail";
    }
    
    @RequestMapping("/logoutuser.html")
    public String logout(HttpSession session){
    	session.removeAttribute("username");
    	session.removeAttribute("user");
    	session.removeAttribute("order");
    	session.removeAttribute("booking");
    	return "home"; 
    }
    
    @SuppressWarnings("unchecked")
	@RequestMapping("/booking.html")
    public String booking(HttpServletRequest request, HttpSession session){
    	
    	String productCode = request.getParameter("code");
    	String page = request.getParameter("page");
    	int productQuantity = Integer.parseInt(request.getParameter("quantity"));
    	Order order = (Order)session.getAttribute("order");	
    	if(order == null){
    		return "userlogin";
    	}else{
    		
    		if(order.getCode() == null){
    			Calendar cal=Calendar.getInstance();
    			int year=cal.get(Calendar.YEAR);
    			long sequence = ws.getMaxOrderKey() + 1;
    		   	order.setCode("CXNT" + year + sequence);
    		   	order.setShipping(10000);
    		}
    		
    		Product product = ws.getProductById(productCode);
        	List<OrderDetail> list = (List<OrderDetail>)session.getAttribute("booking");        	
        	boolean hasProduct = false;
        	
        	for (OrderDetail orderDetail : list) {
				if(orderDetail.getProductCode().equals(productCode)){
					int quantity = orderDetail.getQuantity() + productQuantity;
					long price = product.getNewPrice() * quantity;
					orderDetail.setMaxQuantity(product.getQuantity());
					orderDetail.setQuantity(quantity);
					orderDetail.setPrice(price);
					orderDetail.setUnit(product.getUnit());
					hasProduct = true;
					break;
				}
			}
        	
        	//nếu không tìm thấy product trong list thì mới tạo order detail mới
        	if(!hasProduct){       		
            	OrderDetail detail = new OrderDetail(order.getCode(), productCode, product.getName(), productQuantity, product.getQuantity(), product.getUnit(), product.getNewPrice(), productQuantity*product.getNewPrice());
            	list.add(detail);
        	}
        		
        	long basePrice = ws.computeBasePrice(list);
        	order.setBasePrice(basePrice);
        	order.setShipping(10000);
        	order.setTotalPrice(order.getBasePrice() + order.getShipping());
        	
        	if(page.equals("listproduct"))
        		return "listproduct"; 
        	else if(page.equals("home")){
        		session.setAttribute("address", "listproduct");
        		return "redirect:home.html";
        	}
        		
        	else if(page.equals("listsaleoff"))
        		return "listsaleoff";
        	else if(page.equals("listsearchedproduct"))
        		return "listsearchedproduct";	
        	else
        		return "detailproduct";
        	
    	}
    }
    
    @RequestMapping("/shoppingcard.html")
    public String shoppingPage(HttpSession session){
    	String id = (String)session.getAttribute("username");
    	User user = ws.getUserById(id);
    	session.setAttribute("user", user);
    	return "detailorder"; 

    }
    
    @SuppressWarnings("unchecked")
	@RequestMapping("/editquantity.html")
    public String editQuantity(HttpServletRequest request, HttpSession session){
    	
    	String productCode = request.getParameter("code");
    	int quantity = Integer.parseInt(request.getParameter("quantity"));
    	List<OrderDetail> list = (List<OrderDetail>)session.getAttribute("booking"); 
    	
    	for (OrderDetail orderDetail : list) {
    		System.out.print(orderDetail.getProductCode());
			if(orderDetail.getProductCode().equals(productCode)){
				orderDetail.setQuantity(quantity);
				orderDetail.setPrice(quantity * orderDetail.getUnitPrice());
				break;
			}
		}
    	
    	Order order = (Order)session.getAttribute("order");
    	long basePrice = ws.computeBasePrice(list);
    	order.setBasePrice(basePrice);
    	
    	order.setTotalPrice(order.getBasePrice() + order.getShipping());
    	
    	return "detailorder"; 
    }
    
    @RequestMapping("/moveproductbooking.html")
    public String removeProductBooking(HttpServletRequest request, HttpSession session){
    	
    	String productCode = request.getParameter("id");
    	List<OrderDetail> list = (List<OrderDetail>)session.getAttribute("booking"); 
    	
    	for (OrderDetail orderDetail : list) {
    		System.out.print(orderDetail.getProductCode());
			if(orderDetail.getProductCode().equals(productCode)){
				list.remove(orderDetail);
				break;
			}
		}
    	
    	Order order = (Order)session.getAttribute("order");
    	long basePrice = ws.computeBasePrice(list);
    	order.setBasePrice(basePrice);
    	order.setShipping(0);
    	order.setTotalPrice(order.getBasePrice() + order.getShipping());
    	
    	return "detailorder"; 
    }
    
    @RequestMapping("/moveproductbookinghome.html")
    public String removeProductBookingHome(HttpServletRequest request, HttpSession session){
    	String productCode = request.getParameter("id");
    	List<OrderDetail> list = (List<OrderDetail>)session.getAttribute("booking"); 
    	String address = (String)session.getAttribute("address");
    	
    	for (OrderDetail orderDetail : list) {
    		System.out.print(orderDetail.getProductCode());
			if(orderDetail.getProductCode().equals(productCode)){
				list.remove(orderDetail);
				break;
			}
		}
    	
    	Order order = (Order)session.getAttribute("order");
    	long basePrice = ws.computeBasePrice(list);
    	order.setBasePrice(basePrice);
    	order.setShipping(0);
    	order.setTotalPrice(order.getBasePrice() + order.getShipping());
    	
    	if(address.equals("home")){
    		return "home";
    	}		
    	else if(address.equals("listproduct"))
    		return "listproduct";
    	else if(address.equals("contact"))
    		return "contact";
    	else if(address.equals("introduction"))
    		return "introduction";
    	else if(address.equals("help"))
    		return "help";
    	else if(address.equals("policy"))
    		return "policy";
    	else if(address.equals("listsaleoff"))
    		return "listsaleoff";
    	else if(address.equals("listsaleoff"))
    		return "listsaleoff";
    	else if(address.equals("listsearchedproduct"))
    		return "listsearchedproduct";
    	else if(address.equals("listnotice"))
    		return "listnotice";
    	else if(address.equals("listfood"))
    		return "listfood";
    	else if(address.equals("detailnotice"))
    		return "detailnotice";
    	else if(address.equals("detailfood"))
    		return "detailfood";
    	else
    		return "detailproduct";
    }
    
    @RequestMapping("/editpassworduser")
    public ModelAndView showEditPasswordUserPage(@RequestParam("id") String id, HttpSession session)throws IOException {
    	Workspace ws = new Workspace(AC.VN);
    	mks.webshop.entity.User modUser = ws.getUserById(id);
    	ModelAndView mav = new ModelAndView("editpassworduser");
    	mav.addObject("user", modUser);
    	return mav;
    }
    
    @RequestMapping("/editpassworduser.di")
    public String processEditPasswordUser(HttpSession session, HttpServletRequest req)throws IOException {
    	Workspace ws = new Workspace(AC.VN);
    	String id = req.getParameter("id");
    	String password = req.getParameter("oldpassword");
    	String password1 = req.getParameter("password1");
    	String password2 = req.getParameter("password2");
    	mks.webshop.entity.User temUser = ws.getUserById(id);
    	if (!password.equals(temUser.getPassword())){
    		session.setAttribute("error", 10);
    		return "redirect:editpassworduser.html?id=" + id;
    	} else if (!password1.equals(password2)){
    		session.setAttribute("error", 5);
    		return "redirect:editpassworduser.html?id=" + id;
    	}else {
    		mks.webshop.entity.User modUser = new mks.webshop.entity.User();
        	modUser.setId(id);
        	modUser.setName("");
        	modUser.setEmail("");
        	modUser.setPhonenumber("");
        	modUser.setPassword(password2);
        	ws.save(modUser);
        	return "redirect:detailuser.html?id=" + id;
    	}
    }
    
    @RequestMapping("/editinfouser")
    public ModelAndView showEditInfoUserPage(@RequestParam("id") String id, HttpSession session)throws IOException {
    	Workspace ws = new Workspace(AC.VN);
    	mks.webshop.entity.User modUser = ws.getUserById(id);
    	ModelAndView mav = new ModelAndView("editinfouser");
    	mav.addObject("user", modUser);
    	return mav;
    	
    }
    @RequestMapping("/editinfouser.di")
    public String processEditInfoUser(HttpSession session, HttpServletRequest req)throws IOException {
    	Workspace ws = new Workspace(AC.VN);
    	String id = req.getParameter("id");
    	String name = req.getParameter("name");
    	String email = req.getParameter("email");
    	String phonenumber = req.getParameter("phonenumber");
    	mks.webshop.entity.User modUser = new mks.webshop.entity.User();
    	modUser.setId(id);
    	modUser.setPassword("");
    	modUser.setName(name);
    	modUser.setEmail(email);
    	modUser.setPhonenumber(phonenumber);
    	ws.save(modUser);
    	return "redirect:detailuser.html?id=" + id;
    	
    }
    
    @RequestMapping("/detailorderadmin")
    public ModelAndView showDetailorderPage(@RequestParam("code") String code, HttpSession session){
    	Workspace ws = new Workspace(AC.VN);
    	Order modOrder = ws.getOrderByCode(code);
    	List<OrderDetail> modOrderDetail = ws.getOrderDetailByOrderCode(code);
    	ModelAndView mav = new ModelAndView("detailorderadmin");
    	mav.addObject("order", modOrder);
    	mav.addObject("booking", modOrderDetail);
    	return mav;
    }
    
    @SuppressWarnings("unchecked")
	@RequestMapping("/showproduct.html")
    public String showProduct(HttpServletRequest request, HttpSession session){
    	String address = (String)session.getAttribute("address");
    	List<Product> currentList = (List<Product>) session.getAttribute("proList");
    	List<Product> modList = ws.getAllProductList();
    	List<Product> proList = ws.getProductWithQuantity(modList, currentList.size() + 10);
    	session.removeAttribute("proList");
        session.setAttribute("proList", proList);    
    	return address;
    }
     
    
}
